package com.ebupt.migu.caller.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ebupt.migu.caller.entity.MarketSMSCount;
import com.ebupt.migu.caller.entity.ScheduleBean;
import com.ebupt.migu.caller.mapper.ScheduleMapper;
import com.ebupt.migu.caller.service.CallerHungUpMessageProducerService;
import com.ebupt.migu.common.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Component
public class ScheduleController {

    @Autowired
    private ScheduleMapper mapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private CallerHungUpMessageProducerService service;

    @Scheduled(initialDelay = 3 * 1000, fixedRate = 3 * 60 * 1000)
    public void schedule() {
        List<ScheduleBean> beans = mapper.query();
        if (beans != null) {
            for (ScheduleBean bean : beans) {
                String key = "caller-hung-up-message-" + bean.getStrategyId();
                log.info("当前活动：{}", bean.getStrategyId());
                if (redisTemplate.hasKey(key)) {
                    redisTemplate.delete(key);
                }
                log.info("更新活动配置：{}", bean);
                redisTemplate.opsForValue().set(key, JSON.toJSONString(bean));

                try {
                    if (null != bean.getEndTime() && !"".equals(bean.getEndTime())) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date targetDate = sdf.parse(bean.getEndTime());
                        long endOfDayTimestamp = targetDate.getTime() + 24 * 60 * 60 * 1000 - 1;
                        long currentTimestamp = System.currentTimeMillis();
                        long expirySeconds = (endOfDayTimestamp - currentTimestamp) / 1000;
                        if (expirySeconds > 0) {
                            log.info("刷新活动过期时间：{}", key);
                            redisTemplate.expire(key, expirySeconds, java.util.concurrent.TimeUnit.SECONDS);
                        } else {
                            redisTemplate.delete(key);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Scheduled(initialDelay = 3 * 1000, fixedRate = 24 * 60 * 60 * 1000)
    public void megaMarket() {
        service.refreshMegaMarketConf();
    }

    @Scheduled(initialDelay = 3 * 1000, fixedRate = 3 * 60 * 1000)
    public void count() {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String yesterdayStr = yesterday.format(formatter);
        Set<String> keys = redisTemplate.keys("caller-send-count-" + yesterdayStr + "*");
        if (null != keys) {
            keys.stream().forEach(key -> {
                String activityId = key.split("-")[4];
                HashMap<String, String> info = mapper.qryMarketInfo(activityId);
                log.info("在数据库中获取到的信息：{}", info);
                log.info("当前需要获取的Key：{}", key);
                Integer i = Integer.valueOf(String.valueOf(redisTemplate.opsForValue().get(key)));
                log.info("当前统计值为：{}", i);
                MarketSMSCount marketSMSCount = new MarketSMSCount();
                try {
                    BeanUtils.populate(marketSMSCount, info);
                } catch (Exception e) {
                    log.error("Map转对象异常");
                    e.printStackTrace();
                }
                if (null != info) {
                    marketSMSCount.setCount(i);
                    mapper.insertOrUpdateCount(marketSMSCount);
                    redisTemplate.delete(key);
                }
            });
        }
    }

    private HashMap<String, String> convertKeysToCamelCase(HashMap<String, String> conf) {
        HashMap<String, String> newConf = new HashMap<>();
        for (Map.Entry<String, String> entry : conf.entrySet()) {
            String newKey = convertToCamelCase(entry.getKey());
            newConf.put(newKey, entry.getValue());
        }
        return newConf;
    }

    private String convertToCamelCase(String s) {
        String[] parts = s.split("_");
        StringBuilder camelCase = new StringBuilder(parts[0]);
        for (int i = 1; i < parts.length; i++) {
            camelCase.append(parts[i].substring(0, 1).toUpperCase()).append(parts[i].substring(1));
        }
        return camelCase.toString();
    }
}